package fun.hijklmn.magic.resource.server.filter;

import com.google.common.collect.Sets;
import fun.hijklmn.magic.resource.server.service.MQService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * @Description
 * @Author fs
 * @Date 2021/6/2 11:44
 * @Version 0.0.1-SNAPSHOT
 **/
@Slf4j
@Component
@WebFilter(filterName="countFilter", urlPatterns = {"/*"} )
@Order(0)
public class StatisticFilter implements Filter {

    private Set<String> urls = Sets.newHashSet();

    @Autowired
    private MQService mqService;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestUri = request.getRequestURI();
        if (!urls.contains(requestUri)) {
            log.info("----------->访问地址，requestUri=" + requestUri);
            mqService.send(requestUri);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) {

        RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping) webApplicationContext.getBean("requestMappingHandlerMapping");

        Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = requestMappingHandlerMapping.getHandlerMethods();

        handlerMethodMap.keySet().forEach(requestMappingInfo -> {

            Set<String> patterns = requestMappingInfo.getPatternsCondition().getPatterns();

            urls.addAll(patterns);

        });

    }

    @Override
    public void destroy() {
        urls.clear();
    }

}
